import React, { useEffect, FC } from "react"
import { useRef, useState } from "react"
import { alpha } from "@mui/material/styles"
import { Box, MenuItem, Stack, IconButton } from "@mui/material"
import MenuPopover from "../../components/MenuPopover"
import { useDispatch, useSelector } from "react-redux"
import { languageType, switchLanguage } from "../../store/language/slice"
import { RootState } from "@/store"
import { changeLanguage } from "i18next"

const LANGS = [
  {
    value: "zh_CN" as languageType,
    label: "中文",
    icon: "/static/icons/ic_flag_zh_CN.svg",
  },
  {
    value: "en" as languageType,
    label: "English",
    icon: "/static/icons/ic_flag_en.svg",
  },
]

const LanguagePopover: FC = () => {
  console.log("LanguagePopover rendered...")
  const dispatch = useDispatch()
  const anchorRef = useRef(null)
  const [open, setOpen] = useState(false)
  const currentLanguage = useSelector((state: RootState) => state.lan.language)
  const [currentLanIndex, setCurrentLanIndex] = useState(LANGS.findIndex(item => item.value === currentLanguage))

  const handleOpen = () => {
    setOpen(true)
  }

  const handleClose = () => {
    setOpen(false)
  }

  const handleSelectLanguage = (lan: languageType, index: number) => {
    handleClose()
    setCurrentLanIndex(index)
    dispatch(switchLanguage(lan))
  }

  return (
    <>
      <IconButton
        ref={anchorRef}
        onClick={handleOpen}
        sx={{
          padding: 0,
          width: 44,
          height: 44,
          ...(open && {
            bgcolor: (theme) => alpha(theme.palette.primary.main, theme.palette.action.focusOpacity),
          }),
        }}
      >
        <img width={28} src={LANGS[currentLanIndex].icon} alt={LANGS[currentLanIndex].label} />
      </IconButton>

      <MenuPopover
        open={open}
        onClose={handleClose}
        anchorEl={anchorRef.current}
        sx={{
          mt: 1.5,
          ml: 0.75,
          width: 180,
          "& .MuiMenuItem-root": { px: 1, typography: "body2", borderRadius: 0.75 },
        }}
      >
        <Stack spacing={0.75}>
          {LANGS.map((option, index) => (
            <MenuItem key={option.value} selected={option.value === LANGS[0].value} onClick={() => handleSelectLanguage(option.value, index)}>
              <Box component="img" alt={option.label} src={option.icon} sx={{ width: 28, mr: 2 }} />

              {option.label}
            </MenuItem>
          ))}
        </Stack>
      </MenuPopover>
    </>
  )
}

export default LanguagePopover
